#include <stdio.h>
#include <mm32_device.h>
#include "MM_Print.h"
#include "MM_Delay.h"
#include "Onboard_LED.h"
#include "Onboard_KEY.h"
#include "ESP8266.h"
#include <ctype.h>
#include <string.h>


char ESP8266_SEND_STR[][200] =
{
    {"AT"},
    //0. 设置Wi-Fi模式为 STA模式
    {"AT+CWMODE=1"},
    //1. 连接到AP，"热点名称","密码"
    {"AT+CWJAP=\"CU_ZDR4\",\"dbamw4wz\""},
    //2. 配置传输模式为 透传模式
    // {"AT+CIPMODE=1"},
    //3. 配置多重连接模式关闭，关闭多路连接
    // {"AT+CIPMUX=0"},
    //4. 配置MQTT服务客户端 username,password
    {"AT+MQTTUSERCFG=0,1,\"NULL\",\"MEMBER-WSW202410141212003170\",\"2b4eb80c3782b8cd2a35c1a2b6ba18e4\",0,0,\"\""},
    //5. clientID
    {"AT+MQTTCLIENTID=0,\"MEMBER-WSW202410141212003170\""},
    //6. 连接服务器
    {"AT+MQTTCONN=0,\"192.168.1.11\",1883,1"},
    //7. 订阅指令
    {"AT+MQTTSUB=0,\"member/room\",1"},
    //8. 发布消息
    {"AT+MQTTPUB=0,\"member/room\",\"{\\\"message\\\":\\\"online\\\"}\",1,0"},
};

uint8_t Num = 0;
uint8_t KEY_Num = 0;
char mqtt_key[128];


void to_upper(char *str) {
    strcpy(mqtt_key, str); // 缓冲区溢出！
    int i = 0;
    for (i = 0; mqtt_key[i] != '\0'; i++) {
        mqtt_key[i] = toupper(mqtt_key[i]);
    }
    mqtt_key[i] = '\0';
}


void Action_MqttKey()
{
    // Parse_MQTT_Data();
	if(strlen(MQTT_Data) == 0){return;}
    to_upper(MQTT_Data);
	printf("\r\n action=%s",mqtt_key);
    if(strcmp(mqtt_key, "LED1") == 0)
    {
        OnBoard_LED_Toggle(GPIOB, 14);
    }
	if(strcmp(mqtt_key, "LED2") == 0)
    {
        OnBoard_LED_Toggle(GPIOB, 15);
    }
    Clear_MQTT_Data();
}

int main()
{
	MM_InitConsole(9600);
	MM_InitDelay();
	OnBoard_LED_Init();
	OnBoard_KEY_Init();
	ESP8266_Init();
	while(1)
	{
		KEY_Num = OnBoard_KEY_Get();
        if(KEY_Num == 1)
        {
            if(Num <= 6)
            {
                ESP8266_AT_Command(ESP8266_SEND_STR[Num]);
                Num++;
            }    
        }
		if(KEY_Num == 2)
		{
			ESP8266_AT_Command("AT+MQTTPUB=0,\"member/room\",\"{\\\"message\\\":\\\"KEY2\\\"}\",1,0");
		}
		Action_MqttKey();
	}
}